<?php
/*
 * Created on Sep 19, 2007
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
 //logs in if the user was redirected by log in screen.
require('./Model/Functions.php');
require('./Model/BackClass.php');
session_start();
require('./Controller/BackButton.php'); //Must define my class before the session starts.
require('./Controller/SearchButton.php');
selectDatabase();


if(curPageName() == 'AdminHome.php') { //if the website hasn't been initated'
	$_COOKIE['home'] = 'AdminHome'; //home is true when in normal view false when in admin view
	setcookie('home', 'AdminHome');
}
if(curPageName() == 'Home.php') {
	$_COOKIE['home'] = 'Home';
	setcookie('home', 'Home');
}
if(isset($_POST['Username']) & isset($_POST['Pass'])) { 
	setcookie('initated', true);
	//Initalizes Cookie to make it work for the rest of the website
	$username = $_POST['Username'];
	$pass = $_POST['Pass'];
	unset($_POST['Username']);
	unset($_POST['Pass']);
	$result = selectFromDatabase(array("User", "pass", "Admin"), "Users", array("User"=> $username, "Pass" => $pass));
	//Any new user types the get set here must be unset in the Clear_Cookies
	if (queryExists($result)) {
		setcookie("enabled", "true");
		$showHome = true;
		$line = mysql_fetch_array($result);	
		if($line['Admin'] == 'Debug') {
			setcookie("Debug", "true");
			$_COOKIE['Debug'] = true;
		}
		if($line['Admin'] == 'Guest') {
			setcookie("Guest", "true");
			$_COOKIE['Guest'] = true;
		}
		if($line['Admin'] == 'User') {
			setcookie("User", "true");
			$_COOKIE['User'] = true;
		}
		if($line['Admin'] == "Admin" || $line['Admin'] =="Helper") { //if admin is true in the mysql database.
			setcookie("Helper", "true");
			$_COOKIE['Helper'] = true;
			if($line['Admin'] == "Admin") {
				setcookie("Admin", "true");
				$_COOKIE['Admin'] = true;
			}
		}
		$_COOKIE['enabled'] = true;
	} else {
		echo "Wrong Username or Password. </br>";
	}
}

//Clears back cookie on logout - php style
if(isset($_POST['Logout'])) {
	// unset cookies
	if (isset($_SERVER['HTTP_COOKIE'])) {
	    $cookies = explode(';', $_SERVER['HTTP_COOKIE']);
	    foreach($cookies as $cookie) {
	        $parts = explode('=', $cookie);
	        $name = trim($parts[0]);
	        setcookie($name, '', time()-1000);
	        setcookie($name, '', time()-1000, '/');
	    }
	}

}
?>
<script type="text/javascript">
function test(strDate) {
	alert(strDate)
}
function validate_form(thisform) {	
	table = thisform.table.value
	//Must include size
	if (!(document.pressed == 'ignore')) { //If something is specfied to be ignores disable the entire script
		if(document.pressed=='clear') {
			if(!confirm("Are you sure you want to clear the entire box?")) {
				return false;
			}
			document.pressed='question'
		}
		if (!(document.pressed == 'question')) {
			if(table == "FrozenTubeID") {
					var strDate = thisform.FrozenDate.value
					if(isDate(strDate) == false) {
						return false;
					}
			} else {
				var size = thisform.size.value
					for( i=1;i<=size;i++) { //be posting because row count starts at 1 instead of zero
					var varName = i + "[Name]"
					var nameValue = thisform [varName].value
					if (table=="CellType") {
						if(nameValue == null || nameValue =="") {
							alert("Please enter a name")
							return false
						}
					} else if(table=="Modification") {
						if(nameValue == null || nameValue =="") {
							alert("Please enter a Name")
							return false;
						}
					} else if(table=="Container") {	
						var varTable = i + "[Table]"
						var tableValue = thisform [varTable].value
						var varTower = i + "[Tower]"
						var varPosition = i+ "[Position]"
						var towerValue = thisform [varTower].value
						var positionValue = thisform [varPosition].value
						if(tableValue == null || tableValue =="") {
							alert("Please enter a tank")
							return false;
						}
						if(tableValue == null || tableValue =="") {
							alert("Please enter a tower")
							return false;
						}
						if(positionValue == null || positionValue =="") {
							alert("Please enter a position")
							return false;
						}
					} else if(table == "Users") {			
						var varPosition = i + "[User]"
						var varPass = i + "[pass]"
						var varPass2 = i + "[pass2]"
						var positionValue = thisform [varPosition].value
						var passValue = thisform [varPass].value
						var pass2Value = thisform [varPass2].value
						if(positionValue == null || positionValue =="") {
							alert("Please enter a Name")
							return false;
						}
						if(passValue == null || passValue =="") {
							alert("Please enter a password")
							return false;
						}
						if(pass2Value == null || pass2Value =="") {
							alert("Please enter confirmaion of password")
							return false;
						}
						if(passValue != pass2Value) {
							alert("Passwords do not match")
							return false;
						}
					} else if(table == "Researcher") {
						var varEmail = i + "[Email]"
						var emailValue = thisform [varEmail].value
						
						if(nameValue == null || nameValue == "") {
							alert("Please enter a Name")
							return false;
						}
						//if ((emailValue==null)||(emailValue=="")){
							//alert("Please Enter your Email")
							//return false
						//}
						if ((echeck(emailValue)==false) && (emailValue.length!=0)){
							alert("Invalid E-mail")
							return false
						}
						return true
					}  else if(table == "ContainerType") {
						var varNumCols = i + "[numCols]"
						var varNumRows = i + "[numRows]"
						var numColsValue = thisform [varNumCols].value
						var numRowsValue = thisform [varNumRows].value
						numColsValue = Number(numColsValue)
						if(numColsValue == null || numColsValue == "" || numRowsValue == null || numRowsValue == "") {
							alert("Please enter a valid number")
							return false;
						}
						if(isNaN(numColsValue) || isNaN(numRowsValue)) {
							alert("Please enter a valid number")
							return false;
					}
						
		
					}
				}	
			}
		}
		if(!confirm("Are you sure you want to Continue?")) {
			return false;
		}
	}
}
		
function Set_Cookie( name, value, expires, path, domain, secure ) 
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	
	/*
	if the expires variable is set, make the correct 
	expires time, the current script below will set 
	it for x number of days, to make it for hours, 
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
	expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
	( ( path ) ? ";path=" + path : "" ) + 
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}
			

// this fixes an issue with the old method, ambiguous values 
// with this test document.cookie.indexOf( name + "=" );
function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
		
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}				
		

// this function gets the cookie, if it exists
// don't use this, it's weak and does not handle some cases
// correctly, this is just to maintain legacy information
function Get_Cookie( name ) {
	
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) &&
	( name != document.cookie.substring( 0, name.length ) ) )
	{
	return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
	}
	
	// this deletes the cookie when called
	
	function Delete_Cookie( name, path, domain ) {
	if ( Get_Cookie( name ) ) document.cookie = name + "=" +
	( ( path ) ? ";path=" + path : "") +
	( ( domain ) ? ";domain=" + domain : "" ) +
	";expires=Thu, 01-Jan-1970 00:00:01 GMT";
	}
function ClearCookies() 
{
	Delete_Cookie("enabled");
	Delete_Cookie("Admin");
	Delete_Cookie("Helper");
	Delete_Cookie("Debug");
	Delete_Cookie("prevPage");
	Delete_Cookie("Guest");
	Delete_Cookie("User");
	Delete_Cookie("back");
	Delete_Cookie("initated");
	Delete_Cookie('notfirstClickBack');
	window.location.reload()

}
function Print() {
	document.body.offsetHeight;
	windown.print();
}
	/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	strMonthOld = strMonth
	strDayOld = strDay
	
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	
	if (pos1==-1 || pos2==-1){
		alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonthOld.length<2 || month<1 || month>12){
		alert("Please enter a valid month. \nThe date format should be : mm/dd/yyyy")
		return false
	}
	if (strDayOld.length<2 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day. \nThe date format should be : mm/dd/yyyy")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date")
		return false
	}
return true
}

function echeck(str) {

		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   //alert("Invalid E-mail")
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		  // alert("Invalid E-mail")
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		   // alert("Invalid E-mail")
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		   // alert("Invalid E-mail")
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    //alert("Invalid E-mail")
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    //alert("Invalid E-mail")
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    //alert("Invalid E-mail")
		    return false
		 }
 		 return true					
	}
</script>
<?php if (!$_COOKIE['enabled']): ?>
Please Log in <br>
<form action='Home.php' method="post" name="LogIn">
<input type="text" name="Username" value="Username">
</br>
<input type="password" name="Pass" value="">
</br>
<input type="submit" value="Login" name="login">
<? die; ?>
<?php else: ?>
<table>
	<tr>
		<td>
		<a href=Home.php><font size="2">Overview (Clear Search)</a>
		</td>
		<td>
			|
		</td>
		<td>
		<a href=Home.php?<?php echo makeSearchLink($_GET, false) ?>><font size="2">Overview (Save Search)</a>
		</td>
		<td>
		|
		</td>
		<?php if(isset($_COOKIE["Helper"])): ?>
			<td>
				<a href=AdminHome.php><font size="2">Administrative Overview</a> 
			</td>
			<td>
			|
			</td>
			
			<?php if($_COOKIE['home'] == 'AdminHome'): ?>
			<td>		
				<a href=AdminAddorEdit.php?edit=CellType><font size="2">Edit Cell Types</a> 
			</td>
			<td>
			|
			</td>
			<td>
				<a href=AdminAddorEdit.php?edit=Modification><font size="2">Edit Modifications</a> 
			</td>
			<td>
			|
			</td>
			<td>
				<a href=AdminAddorEdit.php?edit=Researcher><font size="2">Edit Researchers</a> 
			</td>
			<td>
			|
			</td>
			<td>
				<a href=AdminAddorEdit.php?edit=Container><font size="2">Edit Containers</a> 
			</td>
			<td>
			|
			</td>
			<td>
				<a href=AdminAddorEdit.php?edit=ContainerType><font size="2">Edit Container Types</a> 
			</td>
			<td>
				|
			</td>
			<?php if(isset($_COOKIE["Admin"])): ?>
				
				<td>
					<a href=AdminAddorEdit.php?edit=Users><font size="2">Edit Users</a>
				</td>
				<td>
				|
				</td>
				<?php endif; ?>
			<?php endif; ?>
		<?php endif; ?>
		<td valign="bottom"> </br>
			<?php makeBackButton() ?> 
		</td>
		<td>
		|
		</td>
		<td>
			<form name="logout" action="Home.php" method="post" > </br>
			<input type="submit" name="Logout" value="Logout" onclick="ClearCookies()">
			</form>
		<td>
	</tr>
</table>
</font>

<?php endif; ?>
<?php //echo print_r($_COOKIE)  //for debugging?>
<?php //echo print_r($_SESSION) ?>
<?php //echo "</br> Session id is " . session_id() . "</br>"?>